const Koa=require('koa');
const Router=require('koa-router');
const static=require('./routers/stastic');
const body=require('koa-better-body');
const path=require('path');
const session=require('koa-session');
const fs=require('fs');
const ejs=require('koa-ejs');
const config=require('./config');
let server=new Koa();
server.listen(config.PORT);

//中间件
server.use(body({
     uploadDir:path.resolve(__dirname,'./static/upload')
 }));

server.keys=fs.readFileSync('.keys').toString().split('\n');
server.use(session({
    maxAge:20*60*1000,  //最长时间
    renew:true  //自动续期
},server))

//数据库
server.context.db=require('./libs/database');

//公共路径绑定到ctx上
server.context.config=config;

//渲染
ejs(server,{
    root:path.resolve(__dirname,'template'),
    layout:false,
    viewExt:'ejs',
    cache:false,
    debug:false
})

//路由和static
let router=new Router();

//统一处理
router.use(async (ctx,next)=>{
    try{
        await next();

        //正常
    }catch(e){
        // ctx.state=500;
        // ctx.body="服务器出错"
        console.log(e);
        ctx.throw(500,"服务器出错");
    }
})

router.use('/admin',require('./routers/admin'));
router.use('/api',require('./routers/api'));
router.use('',require('./routers/www'));
static(router)

server.use(router.routes());